package com.yl.order.ui.fragment;

import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yl.common.ui.BaseFragment;
import com.yl.order.R;
import com.yl.order.db.entity.CategoryEntity;
import com.yl.order.db.entity.SpecEntity;
import com.yl.order.interfaces.Callback;
import com.yl.order.model.SyncModel;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * create by cjx on 2024/11/6
 * desc: 选择规格的碎片
 */
public class SubSpecSelectFragment2 extends BaseFragment implements View.OnClickListener {

    private TextView[] selectViewArray;
    private ArrayList<ArrayList<TextView>> itemViews;

    // 列数
    private int column = 3;

    // 样式
    private int padding;
    private int textSize;
    private int itemHeight;
    private int titleWidth;
    private ColorStateList colorStateList;

    // 规格过滤选项
    private boolean lock = false; //锁定点击事件
    // 规格默认选中
    private HashSet<String> defaultSpec;
    private List<HashSet<String>> specSetList; // 商品可选规格列表

    private int position = 0;
    private Callback<ArrayList<SpecEntity>> callback;

    public static SubSpecSelectFragment2 newInstance() {
        SubSpecSelectFragment2 specSelectFragment = new SubSpecSelectFragment2();
        specSelectFragment.saveStatusLog = false;
        return specSelectFragment;
    }

    @Override
    public int getViewId() {
        return 0;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getContext() == null) {
            return null;
        }
        LinearLayout groupView = new LinearLayout(getContext());
        groupView.setOrientation(LinearLayout.VERTICAL);
        initSpecView(groupView);
        return groupView;
    }

    @Override
    public void afterViewShow() {
    }

    @Override
    public void onClick(View v) {
        if (lock || v.isSelected()) {
            return;
        }
        onSpecClick((TextView) v);
        if (callback != null) {
            callback.callback(getSelectSpec());
        }
    }

    public void lockView() {
        this.lock = true;
    }

    public ArrayList<SpecEntity> getSelectSpec() {
        ArrayList<SpecEntity> selectList = new ArrayList<>();
        if (selectViewArray == null) {
            return selectList;
        }
        for (TextView textView : selectViewArray) {
            if (textView == null) {
                continue;
            }
            selectList.add((SpecEntity) textView.getTag());
        }
        return selectList;
    }

    public SubSpecSelectFragment2 setColumn(int column) {
        this.column = column;
        return this;
    }

    public SubSpecSelectFragment2 lockSpec(boolean lockSpec) {
        this.lock = lockSpec;
        return this;
    }

    public SubSpecSelectFragment2 setSelectChangedCallback(Callback<ArrayList<SpecEntity>> callback) {
        this.callback = callback;
        return this;
    }

    public SubSpecSelectFragment2 setSpecSetList(List<HashSet<String>> specSetList) {
        this.specSetList = specSetList;
        return this;
    }

    public SubSpecSelectFragment2 setDefaultSpec(HashSet<String> defaultSpec) {
        this.defaultSpec = defaultSpec;
        return this;
    }

    private void initSpecView(ViewGroup parent) {
        Context context = parent.getContext();
        if (padding == 0 && textSize == 0 && itemHeight == 0) {
            padding = getResources().getDimensionPixelSize(R.dimen.dp_12);
            textSize = getResources().getDimensionPixelSize(R.dimen.sp_10);
            itemHeight = getResources().getDimensionPixelSize(R.dimen.dp_32);
            titleWidth = getResources().getDimensionPixelOffset(R.dimen.dp_45);
        }
        ArrayList<CategoryEntity> specGroup = SyncModel.getSpecCategoryList();
        selectViewArray = new TextView[specGroup.size()];
        colorStateList = getResources().getColorStateList(R.color.checkbox_text_color);
        itemViews = new ArrayList<>();

        for (int i = 0; i < specGroup.size(); i++) {
            ArrayList<TextView> viewList = new ArrayList<>();
            itemViews.add(viewList);
            CategoryEntity g = specGroup.get(i);
            initSpecGroupView(i, parent, context, g, viewList);
        }

        if (defaultSpec == null) {
            // 设置默认选中的规格
            if (specSetList != null && !specSetList.isEmpty()) {
                defaultSpec = specSetList.get(0);
            }
        }
        HashSet<String> prevNumberSet = new HashSet<>();

        for (int i = 0; i < itemViews.size(); i++) {
            setEnableView(i, prevNumberSet);
        }
        if (callback != null) {
            callback.callback(getSelectSpec());
        }
    }

    private void setEnableView(int index, HashSet<String> prevNumberSet) {
        HashSet<String> enableNumber = new HashSet<>();
        boolean defaultSpecExist = false; // 标识默认规格是否存在配方
        HashSet<String> firstFormulaSet = null; // 预存第一个匹配到点击的配方规格，如果默认规格不存在，则用这个替换
        for (HashSet<String> formulaSet : specSetList) {
            if (!defaultSpecExist) {
                defaultSpecExist = formulaSet.containsAll(defaultSpec) && formulaSet.size() == defaultSpec.size();
            }
            if (formulaSet.containsAll(prevNumberSet)) {
                if (firstFormulaSet == null) {
                    firstFormulaSet = formulaSet;
                }
                enableNumber.addAll(formulaSet);
            }
        }
        if (!defaultSpecExist) {
            defaultSpec = firstFormulaSet;
        }
        // 处理规格里面的view是否启用和选中
        ArrayList<TextView> viewList = itemViews.get(index);
        String selectNumber = null;
        TextView prevSelectView = selectViewArray[index];
        if (prevSelectView != null) {
            prevSelectView.setSelected(false);
            selectViewArray[index] = null;
        }
        for (TextView v : viewList) {
            String number = ((SpecEntity) v.getTag()).getNumber();
            boolean enable = enableNumber.contains(number);
            if (defaultSpec.contains(number)) {
                v.setSelected(true);
                selectViewArray[index] = v;
                selectNumber = number;
                v.setEnabled(true);
            } else {
                v.setEnabled(enable && !lock);
            }
        }
        if (selectNumber != null) {
            prevNumberSet.add(selectNumber);
        }
    }

    private void initSpecGroupView(int index, ViewGroup parent, Context context, CategoryEntity g, ArrayList<TextView> viewList) {
        List<SpecEntity> specList = SyncModel.getSpecList(g.getNumber());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        if (specList.isEmpty()) {
            return;
        }

        RelativeLayout itemGroupView = new RelativeLayout(context);
        itemGroupView.setPadding(padding, 0, padding, 0);
        if (position > 0) {
            layoutParams.topMargin = padding / 2;
        }
        parent.addView(itemGroupView, position++, layoutParams);
        int groupViewId = View.generateViewId();
        TextView groupView = new TextView(context);
        groupView.setId(groupViewId);
        groupView.setGravity(Gravity.CENTER_VERTICAL);
        groupView.setTextColor(ContextCompat.getColor(context, R.color.text_title_dark));
        groupView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        groupView.setText(g.getName());
        itemGroupView.addView(groupView, new ViewGroup.LayoutParams(titleWidth, itemHeight));

        int size = specList.size();
        int line = (size + column - 1) / column;
        int[] itemContainerId = new int[line];
        for (int i = 0; i < line; i++) {
            LinearLayout linearLayout = initItemContainerView(index, context, i, specList, viewList);
            int cid = View.generateViewId();
            linearLayout.setId(cid);
            itemContainerId[i] = cid;
            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            rlp.addRule(RelativeLayout.END_OF, groupViewId);
            if (i > 0) {
                rlp.topMargin = padding / 4;
                rlp.addRule(RelativeLayout.BELOW, itemContainerId[i - 1]);
            }
            itemGroupView.addView(linearLayout, i, rlp);
        }
    }

    private LinearLayout initItemContainerView(int index, Context context, int i, List<SpecEntity> specList, ArrayList<TextView> viewList) {
        LinearLayout linearLayout = new LinearLayout(context);
        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(0, itemHeight, 1);
        llp.rightMargin = padding / 2;
        for (int j = 0; j < column; j++) {
            int itemPosition = i * column + j;
            if (itemPosition >= specList.size()) {
                View v = new View(context);
                linearLayout.addView(v, llp);
                continue;
            }
            SpecEntity entity = specList.get(itemPosition);
            TextView itemView = initItemView(index, context, entity);
            viewList.add(itemView);
            linearLayout.addView(itemView, llp);
        }
        return linearLayout;
    }

    private void onSpecClick(TextView view) {
        SpecEntity spec = (SpecEntity) view.getTag();
        int index = 0;
        HashSet<String> prevNumberSet = new HashSet<>();
        HashSet<String> selectFormula = new HashSet<>();
        boolean found = false;
        for (int i = 0; i < selectViewArray.length; i++) {
            TextView selectView = selectViewArray[i];
            if (selectView == null) {
                continue;
            }
            SpecEntity selectSpec = (SpecEntity) selectView.getTag();
            if (!found) {
                if (selectSpec.getGroupNumber().equals(spec.getGroupNumber())) {
                    found = true;
                    index = i;
                    selectView.setSelected(false);
                    selectViewArray[i] = view;
                    view.setSelected(true);
                    prevNumberSet.add(spec.getNumber());
                    selectFormula.add(spec.getNumber());
                    continue;
                } else {
                    prevNumberSet.add(selectSpec.getNumber());
                }
            }
            selectFormula.add(selectSpec.getNumber());
        }
        // 设置默认的配方规格
        defaultSpec = selectFormula;
        for (int i = index + 1; i < itemViews.size(); i++) {
            setEnableView(i, prevNumberSet);
        }
    }

    private TextView initItemView(int index, Context context, SpecEntity entity) {
        TextView itemView = new TextView(context);
        itemView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        itemView.setGravity(Gravity.CENTER);
        itemView.setBackgroundResource(R.drawable.checkbox_border);
        itemView.setTextColor(colorStateList);
        itemView.setText(entity.getName());
        itemView.setOnClickListener(this);
        itemView.setTag(entity);
        return itemView;
    }
}
